package com.net.oil.car;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import androidx.viewpager.widget.ViewPager;
import androidx.core.widget.NestedScrollView;
import
androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.net.oil.R;
import com.net.oil.app.Constant;
import com.net.oil.base.BaseActivity;
import com.net.oil.base.CarTypeMessage;
import com.net.oil.car.CardViewPager.CardPagerAdapter;
import com.net.oil.car.CardViewPager.CardViewPager;
import com.net.oil.car.adapter.UseSubsidiaryRecyclerViewAdapter;
import com.net.oil.car.bean.CarBean;
import com.net.oil.car.contract.MyCarDetailContract;
import com.net.oil.car.presenter.MyCarDetailPresenter;
import com.net.oil.http.AppUrl;
import com.net.oil.oilWear.OilWearActivity;
import com.net.oil.order.MaintainListActivity;
import com.net.oil.product.ProductDetailActivity;
import com.net.oil.shop.ShopDetailActivity;
import com.net.oil.shop.ShopListActivity;
import com.net.oil.util.DateFormat;
import com.net.oil.util.DisplayUtil;
import com.net.oil.util.StringUtil;
import com.net.oil.util.glide.GlideUtil;
import com.net.oil.widget.ToastUtil;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

public class MyCarDetailActivity extends BaseActivity<MyCarDetailPresenter> implements MyCarDetailContract.View {

    @BindView(R.id.toolbar_go_back)
    ImageView toolbarGoBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.card_view_pager)
    CardViewPager cardViewPager;
    @BindView(R.id.banner_dot_group)
    RadioGroup bannerDotGroup;
    @BindView(R.id.add_car_iv)
    ImageView addCarIv;
    @BindView(R.id.toolbar_layout)
    Toolbar toolbarLayout;
    @BindView(R.id.button_layout)
    LinearLayout buttonLayout;
    @BindView(R.id.road_haul)
    TextView roadHaul;
    @BindView(R.id.buy_car_time)
    TextView buyCarTime;
    @BindView(R.id.engine_displacement_tv)
    TextView engineDisplacementTv;
    @BindView(R.id.car_type_tv)
    TextView carTypeTv;
    @BindView(R.id.gearbox_model_tv)
    TextView gearboxModelTv;
    @BindView(R.id.car_number_tv)
    TextView carNumberTv;
    @BindView(R.id.car_flag_number_tv)
    TextView carFlagNumberTv;
    @BindView(R.id.delete_car_tv)
    TextView deleteCarTv;
    @BindView(R.id.set_default_car_tv)
    TextView setDefaultCarTv;
    @BindView(R.id.add_car_hint_tv)
    TextView addCarHintTv;
    @BindView(R.id.car_info_rl)
    NestedScrollView carInfoRl;
    @BindView(R.id.maintain_record)
    TextView maintainRecord;
    @BindView(R.id.order_maintain)
    TextView orderMaintain;
    @BindView(R.id.keep_time_tv)
    TextView keepTimeTv;
    @BindView(R.id.keep_shop_tv)
    TextView keepShopTv;
    @BindView(R.id.oil_img)
    ImageView oilImg;
    @BindView(R.id.keep_oil_tv)
    TextView keepOilTv;
    @BindView(R.id.gearbox_oil_img)
    ImageView gearboxOilImg;
    @BindView(R.id.gearbox_keep_oil_tv)
    TextView gearboxKeepOilTv;
    @BindView(R.id.brake_oil_img)
    ImageView brakeOilImg;
    @BindView(R.id.brake_oil_tv)
    TextView brakeOilTv;
    @BindView(R.id.oil_next_keep_mil_tv)
    TextView oilNextKeepMilTv;
    @BindView(R.id.brake_oil_next_keep_mil_tv)
    TextView brakeOilNextKeepMilTv;
    @BindView(R.id.gearbox_next_keep_mil_tv)
    TextView gearboxNextKeepMilTv;
    @BindView(R.id.next_keep_time_tv)
    TextView nextKeepTimeTv;
    @BindView(R.id.oil_wear_tv)
    TextView oilWearTv;
    @BindView(R.id.subsidiary_product_recycler_view)
    RecyclerView subsidiaryProductRecyclerView;

    private ArrayList<CarBean> carBeans;
    private CardPagerAdapter cardAdapter;
    private CarBean carBean;       //当前位置的carBean;

    private int currentPosition = 0;        //当前爱车的位置

    private CarBean.CarModelInfoBean carInfo;            //车辆信息
    private CarBean.BrakeOilBean brakeOilBean;           //刹车油
    private CarBean.GearboxOilBean gearboxOilBean;          //变速箱油
    private CarBean.OilProductBean oilProductBean;      //保养机油

    private CarBean.UseSubsidiaryProductBean useSubsidiaryProductBean;      //使用的附件

    private UseSubsidiaryRecyclerViewAdapter subsidiaryRecyclerViewAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_car_detail);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        presenter = new MyCarDetailPresenter(this);
        initView();
        initData();
    }

    private void initData() {
        showProgressDialog();
        presenter.getMyCarList();
    }

    private void initView() {

        toolbarTitle.setText(getString(R.string.my_car));

        int mWidth = Resources.getSystem().getDisplayMetrics().widthPixels;

        cardAdapter = new CardPagerAdapter(getApplicationContext(), mWidth);


        int maxFactor = mWidth / 16;
        cardAdapter.setMaxElevationFactor(maxFactor);

        int mWidthPadding = mWidth / 8;

        cardViewPager.setPadding(mWidthPadding, 0, mWidthPadding, 0);
        cardViewPager.setClipToPadding(false);
        cardViewPager.setAdapter(cardAdapter);
        cardViewPager.showTransformer(0.2f);

        maintainRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (carBean != null) {
                    Intent intent = new Intent(MyCarDetailActivity.this, MaintainListActivity.class);
                    intent.putExtra(Constant.INTENT_CAR_ID, carBean.getId());
                    startActivity(intent);
                }
            }
        });

        orderMaintain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyCarDetailActivity.this, ShopListActivity.class);
                intent.putExtra(Constant.INTENT_CAR_ID, carBean.getId());
                intent.putExtra(Constant.INTENT_CAR_TYPE, carBean.getCarModelInfo().getType());
                startActivity(intent);
            }
        });

        oilWearTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (carBeans != null) {
                    Intent intent = new Intent(MyCarDetailActivity.this, OilWearActivity.class);
                    Gson gson = new Gson();
                    String json = gson.toJson(carBeans);
                    intent.putExtra(OilWearActivity.INTENT_CAR_LIST_KEY, json);
                    startActivity(intent);
                }
            }
        });

        subsidiaryRecyclerViewAdapter = new UseSubsidiaryRecyclerViewAdapter(this);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        subsidiaryProductRecyclerView.setLayoutManager(manager);
        subsidiaryProductRecyclerView.setAdapter(subsidiaryRecyclerViewAdapter);

    }

    private void initBannerView() {

        cardViewPager.removeAllViews();
        bannerDotGroup.removeAllViews();

        RadioGroup.LayoutParams buttonParams = new RadioGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        buttonParams.setMargins(DisplayUtil.dip2px(5), 0,
                DisplayUtil.dip2px(5), 0);

        for (int i = 0; i < carBeans.size(); i++) {
            //动态生成RadioButton,设置button属性
            RadioButton button = new RadioButton(this);
            button.setButtonDrawable(null);
            button.setLayoutParams(buttonParams);
            button.setWidth(DisplayUtil.dip2px(6));
            button.setHeight(DisplayUtil.dip2px(6));
            button.setId(i);
            button.setBackgroundResource(R.drawable.banner_dot_bg_selector);
            if (i == 0) {
                button.setChecked(true);
            }
            bannerDotGroup.addView(button);

            //如果只有一条轮播数据，则隐藏圆点
            if (i < 1) {
                if (bannerDotGroup.getVisibility() == View.VISIBLE) {
                    bannerDotGroup.setVisibility(View.GONE);
                }
            } else {
                if (bannerDotGroup.getVisibility() == View.GONE) {
                    bannerDotGroup.setVisibility(View.VISIBLE);
                }
            }
        }
        cardViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                carBean = carBeans.get(position);
                bannerDotGroup.check(position);
                initCarInfoView(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        cardAdapter.updateData(carBeans);
        cardViewPager.setOffscreenPageLimit(carBeans.size());
        cardViewPager.setCurrentItem(0);
    }

    /**
     * 设置车辆信息
     */
    private void initCarInfoView(int position) {
        currentPosition = position;
        carBean = carBeans.get(position);

        if (carBean != null) {

            carInfo = carBean.getCarModelInfo();
            brakeOilBean = carBean.getBrakeOil();
            gearboxOilBean = carBean.getGearboxOil();
            oilProductBean = carBean.getOilProduct();

            roadHaul.setText(String.valueOf(carBean.getMileage()) + "KM");      //里程数

            /* 上次保养时间 */
            if (carBean.getLastKeepTime() != 0) {
                keepTimeTv.setText(DateFormat.formatDateTime(carBean.getLastKeepTime(), DateFormat.FormatFlag.YDM));
            } else {
                keepTimeTv.setText("");
            }


            /* 下次保养时间 */
            if (!StringUtil.isEmpty(carBean.getNextKeepCarDate())) {
                nextKeepTimeTv.setText(carBean.getNextKeepCarDate());
            } else {
                nextKeepTimeTv.setText("");
            }

            /* 上次保养商家 */
            if (!TextUtils.isEmpty(carBean.getLastKeepBusinessName())) {
                keepShopTv.setText(carBean.getLastKeepBusinessName());
            } else {
                keepShopTv.setText("");
            }


            /* 上次保养使用机油 */
            if (oilProductBean != null) {
                /* 机油图片 */
                if (!TextUtils.isEmpty(oilProductBean.getImage())) {
                    GlideUtil.getInstance().loadImage(this, oilImg, AppUrl.getImageUrl(oilProductBean.getImage()),
                            R.drawable.product_err);
                }else {
                    GlideUtil.getInstance().loadImage(this, oilImg, "",
                            R.drawable.product_err);
                }

                /* 上次保养使用机油名称 */
                if (!TextUtils.isEmpty(oilProductBean.getName())) {
                    keepOilTv.setText(oilProductBean.getName());
                } else {
                    keepOilTv.setText("");
                }
            }else {
                GlideUtil.getInstance().loadImage(this, oilImg, "",
                        R.drawable.product_err);
                keepOilTv.setText("");
            }


            /* 上次保养变速箱油 */
            if (gearboxOilBean != null) {
                /* 机油图片 */
                if (!TextUtils.isEmpty(gearboxOilBean.getImage())) {
                    GlideUtil.getInstance().loadImage(this, gearboxOilImg, AppUrl.getImageUrl(gearboxOilBean.getImage()),
                            R.drawable.product_err);
                }else {
                    GlideUtil.getInstance().loadImage(this, gearboxOilImg, "",
                            R.drawable.product_err);
                }

                /* 上次保养变速箱油名称 */
                if (!TextUtils.isEmpty(gearboxOilBean.getName())) {
                    gearboxKeepOilTv.setText(gearboxOilBean.getName());
                } else {
                    gearboxKeepOilTv.setText("");
                }
            }else {
                GlideUtil.getInstance().loadImage(this, gearboxOilImg, "",
                        R.drawable.product_err);
                gearboxKeepOilTv.setText("");
            }

            /* 上次保养刹车油 */
            if (brakeOilBean != null) {
                /* 机油图片 */
                if (!TextUtils.isEmpty(brakeOilBean.getImage())) {
                    GlideUtil.getInstance().loadImage(this, brakeOilImg, AppUrl.getImageUrl(brakeOilBean.getImage()),
                            R.drawable.product_err);
                }else {
                    GlideUtil.getInstance().loadImage(this, brakeOilImg, "",
                            R.drawable.product_err);
                }
                /* 上次保养刹车油名称 */
                if (!TextUtils.isEmpty(brakeOilBean.getName())) {
                    brakeOilTv.setText(brakeOilBean.getName());
                } else {
                    brakeOilTv.setText("");
                }

            }else {
                GlideUtil.getInstance().loadImage(this, brakeOilImg, "",
                        R.drawable.product_err);
                brakeOilTv.setText("");
            }
            /* 下次机油保养里程 */
            if (carBean.getOilNextKeepMileage() != null) {
                oilNextKeepMilTv.setText(String.format(getString(R.string.next_keep_mileage), String.valueOf(carBean.getOilNextKeepMileage())));
            }else {
                oilNextKeepMilTv.setText("");
            }
            /* 下次刹车油保养里程 */
            if (carBean.getBrakeOilNextKeepMileage() != null) {
                brakeOilNextKeepMilTv.setText(String.format(getString(R.string.next_keep_mileage), String.valueOf(carBean.getBrakeOilNextKeepMileage())));
            }else {
                brakeOilNextKeepMilTv.setText("");
            }

            /* 下次变速箱油保养里程、 */
            if (carBean.getGearboxOilNextKeepMileage() != null) {
                gearboxNextKeepMilTv.setText(String.format(getString(R.string.next_keep_mileage), String.valueOf(carBean.getGearboxOilNextKeepMileage())));
            }else {
                gearboxNextKeepMilTv.setText("");
            }

            if (!StringUtil.isEmpty(carBean.getBuyCarTime())) {
                buyCarTime.setText(carBean.getBuyCarTime());        //购车时间
            } else {
                buyCarTime.setText("");        //购车时间
            }

            /* 配件 */
            subsidiaryRecyclerViewAdapter.updateDatas(carBean.getUseSubsidiaryProductItemList());


            if (!StringUtil.isEmpty(carBean.getCarRegistNumber())) {
                carNumberTv.setText(carBean.getCarRegistNumber());      //车牌好
            } else {
                carNumberTv.setText("");      //车牌好
            }

            if (!StringUtil.isEmpty(carBean.getIdentificationCode())) {
                String carFlagNumber = carBean.getIdentificationCode();
                carFlagNumberTv.setText(carFlagNumber);     //车辆识别代码后6位
            } else {
                carFlagNumberTv.setText("");     //车辆识别代码后6位
            }

            if (carBean.isIsDefault()) {
                setDefaultCarTv.setEnabled(false);
            } else {
                setDefaultCarTv.setEnabled(true);
            }

            if (carInfo != null) {
                if (!StringUtil.isEmpty(carInfo.getEmissionsL())) {
                    engineDisplacementTv.setText(carInfo.getEmissionsL());      //排量
                } else {
                    engineDisplacementTv.setText("");      //排量
                }

                if (!StringUtil.isEmpty(carInfo.getType())) {
                    carTypeTv.setText(carInfo.getType());       //车型
                } else {
                    carTypeTv.setText("");       //车型
                }

                if (!StringUtil.isEmpty(carInfo.getGearbox())) {
                    gearboxModelTv.setText(carInfo.getGearbox());   //变速箱型号
                } else {
                    gearboxModelTv.setText("");   //变速箱型号
                }
            }
        }
    }

    private void initCarInfoView() {
        if (carBean != null) {
            CarBean.CarModelInfoBean carInfo = carBean.getCarModelInfo();

            roadHaul.setText(String.valueOf(carBean.getMileage()));      //里程数

            if (!StringUtil.isEmpty(carBean.getBuyCarTime())) {
                buyCarTime.setText(carBean.getBuyCarTime());        //购车时间
            } else {
                buyCarTime.setText("");        //购车时间
            }

            if (!StringUtil.isEmpty(carBean.getCarRegistNumber())) {
                carNumberTv.setText(carBean.getCarRegistNumber());      //车牌号
            } else {
                carNumberTv.setText("");      //车牌好
            }

            if (!StringUtil.isEmpty(carBean.getIdentificationCode())) {
                String carFlagNumber = carBean.getIdentificationCode();
//                String resultStr = carFlagNumber.substring(carFlagNumber.length() - 6, carFlagNumber.length());
                carFlagNumberTv.setText(carFlagNumber);     //车辆识别代码后6位
            } else {
                carFlagNumberTv.setText("");     //车辆识别代码后6位
            }

            if (carBean.isIsDefault()) {
                setDefaultCarTv.setEnabled(false);
            } else {
                setDefaultCarTv.setEnabled(true);
            }
            if (carInfo != null) {
                if (!StringUtil.isEmpty(carInfo.getEmissionsL())) {
                    engineDisplacementTv.setText(carInfo.getEmissionsL());      //排量
                } else {
                    engineDisplacementTv.setText("");      //排量
                }

                if (!StringUtil.isEmpty(carInfo.getType())) {
                    carTypeTv.setText(carInfo.getType());       //车型
                } else {
                    carTypeTv.setText("");       //车型
                }

                if (!StringUtil.isEmpty(carInfo.getGearbox())) {
                    gearboxModelTv.setText(carInfo.getGearbox());   //变速箱型号
                } else {
                    gearboxModelTv.setText("");   //变速箱型号
                }


            }
        }
    }

    @OnClick({R.id.toolbar_go_back, R.id.add_car_iv, R.id.delete_car_tv, R.id.set_default_car_tv,
            R.id.oil_img, R.id.brake_oil_img, R.id.gearbox_oil_img, R.id.keep_shop_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.toolbar_go_back:
                finish();
                break;
            case R.id.add_car_iv:
                startActivity(new Intent(this, SelectCarBrandActivity.class));
                break;
            case R.id.delete_car_tv:
                deleteCar();
                break;
            case R.id.set_default_car_tv:
                setDefaultCar();
                break;
            case R.id.oil_img:
                if (carBean != null && carBean.getOilProductId() != null) {
                    Intent intent1 = new Intent(this, ProductDetailActivity.class);
                    intent1.putExtra(Constant.INTENT_PRODUCT_DETAIL_ID, carBean.getOilProductId());
                    startActivity(intent1);
                }

                break;
            case R.id.brake_oil_img:
                if (carBean != null && carBean.getBrakeOilProfuctId() != null) {
                    Intent intent2 = new Intent(this, ProductDetailActivity.class);
                    intent2.putExtra(Constant.INTENT_PRODUCT_DETAIL_ID, carBean.getBrakeOilProfuctId());
                    startActivity(intent2);
                }

                break;
            case R.id.gearbox_oil_img:
                if (carBean != null && carBean.getGearboxOilId() != null) {
                    Intent intent3 = new Intent(this, ProductDetailActivity.class);
                    intent3.putExtra(Constant.INTENT_PRODUCT_DETAIL_ID, carBean.getGearboxOilId());
                    startActivity(intent3);
                }
                break;
            case R.id.keep_shop_tv:
                Intent intent = new Intent(this, ShopDetailActivity.class);
                if (carBean != null && carInfo != null && carBean.getLastKeepBusinessId() != null) {
                    intent.putExtra(Constant.INTENT_SHOP_ID_KEY, (int) carBean.getLastKeepBusinessId());
                    intent.putExtra(Constant.INTENT_CAR_ID, carInfo.getId());
                    intent.putExtra(Constant.INTENT_CAR_TYPE, carInfo.getType());
                    startActivity(intent);
                }
                break;
        }
    }


    @Subscribe(threadMode = ThreadMode.MainThread)
    public void receiveEventBus(CarTypeMessage message) {
        if (message != null) {
            showProgressDialog();
            presenter.addCar(message.getCarTypeId(), message.getCarNum());
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    /**
     * 添加爱车成功
     */
    @Override
    public void addCarSuccess() {
        dismissProgressDialog();
        ToastUtil.showSuccessToast(this, "添加爱车成功");
        presenter.getMyCarList();
    }

    /**
     * 添加爱车失败
     */
    @Override
    public void addCarFailed() {
        dismissProgressDialog();
    }

    /**
     * 获取爱车列表成功
     *
     * @param carBeans 爱车列表
     */
    @Override
    public void getMyCarListSuccess(List<CarBean> carBeans) {
        dismissProgressDialog();

        ArrayList<CarBean> sortCarBeans = new ArrayList<>();

        for (int i = 0; i < carBeans.size(); i++) {
            if (carBeans.get(i).isIsDefault()) {
                sortCarBeans.add(carBeans.get(i));
                carBeans.remove(i);
            }
        }
        sortCarBeans.addAll(carBeans);

        this.carBeans = sortCarBeans;
        if (sortCarBeans.size() > 0) {
            initBannerView();
            initCarInfoView(currentPosition);
            deleteCarTv.setEnabled(true);

            addCarHintTv.setVisibility(View.GONE);
            carInfoRl.setVisibility(View.VISIBLE);
            buttonLayout.setVisibility(View.VISIBLE);
        } else {
            addCarHintTv.setVisibility(View.VISIBLE);
            carInfoRl.setVisibility(View.GONE);
            buttonLayout.setVisibility(View.GONE);
        }
    }

    /**
     * 获取爱车列表失败
     */
    @Override
    public void getMyCarListFailed() {
        dismissProgressDialog();
    }

    /**
     * 设置默认爱车成功
     */
    @Override
    public void setDefaultCarSuccess() {
        dismissProgressDialog();
        presenter.getMyCarList();
    }

    /**
     * 设置默认爱车失败
     */
    @Override
    public void setDefaultCarFailed() {
        dismissProgressDialog();
        ToastUtil.showErrorToast(this, "设置失败");
    }

    /**
     * 删除爱车成功
     */
    @Override
    public void deleteCarSuccess() {
        dismissProgressDialog();
        presenter.getMyCarList();
    }

    /**
     * 删除爱车失败
     */
    @Override
    public void deleteCarFailed() {
        dismissProgressDialog();
        ToastUtil.showErrorToast(this, "删除失败");
    }

    /**
     * 修改车辆信息成功
     */
    @Override
    public void updateCarInfoSuccess() {
        dismissProgressDialog();
        initCarInfoView();
        ToastUtil.showSuccessToast(this, "修改成功");
    }

    /**
     * 修改车辆信息失败
     */
    @Override
    public void updateCarInfoFailed() {
        dismissProgressDialog();
        ToastUtil.showErrorToast(this, "修改失败");
    }

    /**
     * 设为默认
     */
    private void setDefaultCar() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("你确定设为默认吗？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (currentPosition != -1) {
                    showProgressDialog();
                    presenter.setDefaultCar(carBeans.get(currentPosition).getId());
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.show();
    }

    /**
     * 删除爱车
     */
    private void deleteCar() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("你确定删除爱车吗？");
        builder.setPositiveButton("删除", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (currentPosition != -1) {
                    showProgressDialog();
                    presenter.deleteCar(carBeans.get(currentPosition).getId());
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.show();
    }

    @OnClick({R.id.road_haul, R.id.buy_car_time, R.id.car_number_tv, R.id.car_flag_number_tv})
    public void onUpdateCarInfoClicked(View view) {
        switch (view.getId()) {
            case R.id.road_haul:
                changeRoadHaul("行驶里程", CarInfoKey.ROAD_HAUL, roadHaul.getText().toString().replace("KM", ""));
                break;
            case R.id.buy_car_time:
//                changeRoadHaul("购车时间", CarInfoKey.BUY_TIME);
                selectData("选择购车时间");
                break;
            case R.id.car_number_tv:
                changeRoadHaul("车牌号", CarInfoKey.CAR_NUMBER, carNumberTv.getText().toString());
                break;
            case R.id.car_flag_number_tv:
                changeRoadHaul("车架号", CarInfoKey.IDENTIFICATION_CODE, carFlagNumberTv.getText().toString());
                break;
        }
    }

    /**
     * 弹出修改车辆信息对话框
     *
     * @param title      标题
     * @param carInfoKey 修改的内容
     * @param value      修改之前的信息
     */
    private void changeRoadHaul(String title, final CarInfoKey carInfoKey, String value) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        LinearLayout linearLayout = new LinearLayout(this);
        final EditText editText = new EditText(this);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(DisplayUtil.dip2px(20), 0, DisplayUtil.dip2px(20), 0);
        editText.setLayoutParams(layoutParams);
        editText.setText(value);
        linearLayout.addView(editText);


        switch (carInfoKey) {
            case ROAD_HAUL:
                editText.setInputType(InputType.TYPE_CLASS_NUMBER);
                break;
        }
        builder.setTitle(title);
        builder.setView(linearLayout);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String result = editText.getText().toString();
                if (!StringUtil.isEmpty(result)) {
                    switch (carInfoKey) {
                        case BUY_TIME:
                            carBean.setBuyCarTime(result);
                            break;
                        case CAR_NUMBER:
                            carBean.setCarRegistNumber(result);
                            break;
                        case ROAD_HAUL:
                            carBean.setMileage(Integer.parseInt(result));
                            break;
                        case IDENTIFICATION_CODE:
                            carBean.setIdentificationCode(result);
                            break;
                        case NEXT_KEEP_CAR_DATE:
                            carBean.setNextKeepCarDate(result);
                            break;

                    }
                    updateCarInfo();
                } else {
                    ToastUtil.showErrorToast(MyCarDetailActivity.this, "输入不能为空！");
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.show();

    }

    private void updateCarInfo() {
        if (carBean != null) {
            showProgressDialog();
            presenter.updateCarInfo(carBean.getId(), carBean.getCarRegistNumber(), carBean.getModelId(), carBean.getBuyCarTime(), carBean.getMileage(),
                    carBean.getIdentificationCode(), carBean.getOilName(), carBean.getGearboxOilName(), carBean.getNextKeepCarDate());
        }
    }

    private void selectData(String title) {
        View view = View.inflate(this, R.layout.date_pick, null);
        final DatePicker datePicker = view.findViewById(R.id.date_pick);
        datePicker.setMaxDate(new Date().getTime());

        AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.DialogButtonTheme);
        builder.setTitle(title);
        builder.setView(view);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Calendar calendar = Calendar.getInstance();
                calendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth());
                String date = DateFormat.getStringDateByCalendar(calendar);
                carBean.setBuyCarTime(date);
                updateCarInfo();
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    private enum CarInfoKey {
        CAR_NUMBER,     //车牌号
        BUY_TIME,       //购车时间
        ROAD_HAUL,      //行驶里程
        IDENTIFICATION_CODE,        //车架号
        NEXT_KEEP_CAR_DATE,     //下次保养时间

    }
}
